import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref(null)
    const userList = ref([
      {
        id: 1,
        username: 'admin',
        password: '123456',
        nickname: '管理员',
        email: 'admin@qq.com',
        phone: '13800138000',
        avatar:
          'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        isLogin: false
      }
    ])
    const login = (username, password) => {
      const user = userList.value.find(
        (item) => item.username === username && item.password === password
      )
      if (user) {
        user.isLogin = true
        setUserInfo(user)
        ElNotification({
          title: '登录成功',
          message: '欢迎回来',
          type: 'success'
        })
        return true
      }
      ElNotification({
        title: '登录失败',
        message: '用户名或密码错误',
        type: 'error'
      })
      return false
    }
    const logout = () => {
      userInfo.value.isLogin = false
      clearUserInfo()
    }

    const register = (data) => {
      const user = userList.value.find(
        (item) => item.username === data.username
      )
      if (user) {
        ElNotification({
          title: '注册失败',
          message: '用户名已存在',
          type: 'error'
        })
        return false
      }
      data.isLogin = true
      userList.value.push(data)
      setUserInfo(data)
      ElNotification({
        title: '注册成功',
        message: '欢迎加入',
        type: 'success'
      })
      return true
    }

    const setUserInfo = (data) => {
      userInfo.value = data
    }
    const clearUserInfo = () => {
      userInfo.value = null
    }
    const addUser = (data) => {
      userList.value.push(data)
    }

    const update = (data) => {
      setUserInfo(data)
      userList.value[userList.value.findIndex(i => i.id == data.id)] = data
      ElNotification({
        title: '编辑成功',
        type: 'success'
      })
    }

    const reset = (data) => {
      userList.value[userList.value.findIndex(i => i.username == data.username)].password = data.newPassword
      ElNotification({
        title: '修改成功',
        message: '密码重置成功',
        type: 'success'
      })
      logout()
    }

    return {
      userInfo,
      reset,
      setUserInfo,
      clearUserInfo,
      addUser,
      userList,
      login,
      logout,
      register,
      update
    }
  },
  {
    persist: true
  }
)
